import {request} from '../../../../utils/request';
import api from '../../../../utils/api';
Page({
    data:{
        list:[],
        content: '',
        sessionId: ''
    },
    sendMessage(){
        this.data.list.push({
            id: this.data.list.length,
            question: this.data.content,
            answer: '正在思考...'
        })
        let token = wx.getStorageSync('authentication');
        let requestTask = wx.request({
          url: api.AI_CHAT,
          method: "POST",
          header: token.length == 0 || token == null ? {} : {
            travel: token
          },
          data:{
              question: this.data.content
          },
          enableChunked: true,
          complete: this.ayncMessage()
        });
        this.setData({content: ''});
        this.setData({list: this.data.list});
        requestTask.onChunkReceived(message => {
            const decoder = new TextDecoder('utf-8');
            let answer = decoder.decode(message.data);
            if(answer.startsWith("data:")){
                answer = answer.substring(5, answer.length);
            }
            let list = this.data.list;
            let current = list[list.length - 1] == null ? {} : list[list.length - 1];
            if(current.answer === '正在思考...'){
                current.answer = answer;
            }else{
                current.answer += answer;
            }
            list[list.length - 1] = current;
            this.setData({list: list});
        })
    },

    ayncMessage(){
        let list = this.data.list;
        request(api.AI_SYNCHRONIZE_MESSAGE, {
            sessionId: this.data.sessionId,
            question: list[list.length - 1].question,
            answer: list[list.length - 1].answer
        }, "POST").then(result =>{
            console.log(result.body);
        })
    },
    onLoad(event){
        this.setData({sessionId: event.sessionId});
        
        if(event.question != null){
            this.setData({content: event.question});
            this.sendMessage();
        }else
            this.getHistory();
    },
    getHistory(){
        request(api.AI_CHAT_HISTORY, {sessionId: this.data.sessionId}).then(result =>{
            if(result.code == 200) this.setData({list: result.body});
        })
    }
     
})